package com.fingard.dsp.bank.directbank.cgbunion01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.*;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;

import java.util.HashMap;
import java.util.Map;

public class CGBUnion01JSAPIOrder extends CGB01UnifiedOrder implements IJSAPIOrder {
    @Override
    public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;
        try {
            ActSetItem actItem = this.getBankConfig().getActSetItem(
                    p_req.ownAct, "");
            if (actItem != null) {
                Map<String, String> headMap = buildHeaderParam("unifiedorderJH", actItem);
                Map<String, Object> bodyMap = new HashMap<String, Object>();

                String appid = p_req.appId;
                if ("SubmitMiniProgOrder".equals(p_req.reqHeader.transType)) {
                    bodyMap.put("is_minipg", "UTF-8");
                    bodyMap.put("payWay", "01_WXPAY_XCX");
                    bodyMap.put("service", "gcb.pay.wxPayAndXcx");
                    if (StringHelper.isNullOrEmpty(appid)) {
                        appid = actItem.appIdMap.get("MiniProg");
                    }
                } else if ("SubmitJSAPIOrder".equals(p_req.reqHeader.transType)) {
                    bodyMap.put("payWay", "01_WXPAY_PBPM");
                    bodyMap.put("service", "pay.weixin.jspay");
                    if (StringHelper.isNullOrEmpty(appid)) {
                        appid = actItem.appIdMap.get("JSAPI");
                    }
                }
                bodyMap.put("mch_id", actItem.merchantId);//商户appId
                bodyMap.put("out_trade_no", p_req.rdSeq);
                bodyMap.put("total_fee", StringHelper.amountMultiply100(p_req.amount));
                if (StringHelper.isNullOrEmpty(appid)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "公众号/小程序支付，AppID(应用ID)不可为空";
                    return retAts;
                }
                bodyMap.put("sub_appid", appid);
                if (StringHelper.hasAnyChar(p_req.openid)) {
                    bodyMap.put("sub_openid", p_req.openid);// 用户ID
                } else {
                    if (StringHelper.isNullOrEmpty(p_req.code)) {
                        retAts.respCode = "-1";
                        retAts.respInfo = "Code和Openid不能同时为空";

                        return retAts;
                    } else {
                        if (StringHelper.isNullOrEmpty(actItem.appSecret)) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "未配置appsecret，请检查对应config.xml文件";

                            return retAts;
                        } else {
                            String appSecret = "";
                            if ("SubmitMiniProgOrder".equals(p_req.reqHeader.transType)) {
                                appSecret = actItem.appSecretMap.get("MiniProg");
                            } else if ("SubmitJSAPIOrder".equals(p_req.reqHeader.transType)) {
                                appSecret = actItem.appSecretMap.get("JSAPI");
                            }
                            if (StringHelper.isNullOrEmpty(appSecret)) {
                                retAts.respCode = "-1";
                                retAts.respInfo = "未配置公众号/小程序的appsecret";
                                return retAts;
                            }
                            HashMap<String, String> hashOpenid = getOpenid(appid, appSecret, p_req.code);

                            if (hashOpenid.get("RespCode").equals("0")) {
                                if (hashOpenid.containsKey("openid")) {
                                    bodyMap.put("sub_openid", hashOpenid.get("openid"));
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.payInfoCode = FailCode.E9981;

                                    String errcode = "";
                                    if (hashOpenid.containsKey("errcode")) {
                                        errcode = hashOpenid.get("errcode");
                                    }

                                    String errmsg = "";
                                    if (hashOpenid.containsKey("errmsg")) {
                                        errmsg = hashOpenid.get("errmsg");
                                    }

                                    retAts.respInfo = StringHelper.joinNotEmpty("-", errcode, errmsg);
                                    retAts.transState = PaymentState.FAIL_Payment;

                                    return retAts;
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = hashOpenid.get("RespInfo");

                                return retAts;
                            }
                        }
                    }
                }
                bodyMap.put("is_raw", "1");
                bodyMap.put("mch_create_ip", actItem.createIP);
                if (StringHelper.hasAnyChar(p_req.description)) {
                    String body = XmlHelper.encode(p_req.description);
                    bodyMap.put("body", body);
                }
                bodyMap.put("device_info", "WEB");
                //接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp，确保平台能通过互联网访问该地址
                String notify_url = actItem.notifyURL;

                if (StringHelper.isNullOrEmpty(notify_url)) {
                    notify_url = bankFront.getUrl("unifiedorderNotify");
                }
                if (StringHelper.hasAnyChar(notify_url)) {
                    bodyMap.put("notify_url", notify_url);
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "通知地址notify_url未配置，请检查对应config.xml文件";
                    return retAts;
                }
                if (StringHelper.hasAnyChar(p_req.timeStart)) {
                    bodyMap.put("time_start", p_req.timeStart);
                }
                //	订单失效时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。时区为GMT+8 beijing。该时间取自商户服务器。注：订单生成时间与超时时间需要同时传入才会生效。
                if (StringHelper.hasAnyChar(p_req.timeExpire)) {
                    bodyMap.put("time_expire", p_req.timeExpire);
                }
                boolean limit = getBankConfig().getValueAsBool("limitPay");
                WriteBankUrlLogLn("招商聚合能否用信用卡支付：" + limit);
                if (!limit) {
                    bodyMap.put("limit_credit_pay", "1");
                }
                //商户附加信息，可做扩展参数
                if (StringHelper.hasAnyChar(p_req.attach)) {
                    bodyMap.put("attach", p_req.attach);
                }
                bodyMap.put("nonce_str", get_nonce_str());
                bodyMap.put("sign", "asdf");
                JSONObject preOrder = new JSONObject();
                preOrder.put("Header", headMap);
                preOrder.put("Body", bodyMap);

                String returnStr = send(preOrder, "unifiedorderJH", actItem);

                JSONObject resultObj = JSONObject.parseObject(returnStr);
                JSONObject resBody = resultObj.getJSONObject("Body");
                if (!resBody.containsKey("errorCode")) {
                    retAts.respCode = "0";
                    retAts.customHashMap = new HashMap<String, String>();
                    JSONObject payInfo = resBody.getJSONObject("pay_info");
                    retAts.customHashMap.put("appId", payInfo.getString("appId"));
                    retAts.customHashMap.put("nonceStr", payInfo.getString("nonceStr"));
                    retAts.customHashMap.put("timeStamp", payInfo.getString("timeStamp"));
                    retAts.customHashMap.put("package", payInfo.getString("package"));
                    retAts.customHashMap.put("signType", payInfo.getString("signType"));
                    retAts.customHashMap.put("paySign", payInfo.getString("paySign"));
                } else {
                    retAts.respCode = resBody.getString("errorCode");
                    retAts.respInfo = resBody.getString("errorMsg");
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

    @Override
    public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
        return queryUnifiedOrder(p_req);
    }

    @Override
    public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
        return null;
    }
}
